<template>
    <div class="login">
      <div class="title">登陆页</div>
      <div class="block">
        <input type="text" v-model="formData.phone" placeholder="输入手机号">
      </div>
      <div class="block">
        <input type="password" v-model="formData.pass" placeholder="输入密码">
      </div>
      <div class="block">
        <input type="button" value="登陆" @click="login">
      </div>
    </div>
  </template>
  
  <script>
  import {user_login} from '../../utils/api'
  
  export default {
    data(){
      return {
        formData:{
          phone:'',
          pass:''
        }
      }
    },
    methods:{
      login(){
        if( /^1[3-9]\d{9}$/.test( this.formData.phone ) == false ){
          alert('请输入合法的手机号');
        }else if( !this.formData.pass ){
          alert('请输入密码')
        }else{ //验证通过 
          //发起登陆请求
          user_login( this.formData ).then((res)=>{
            if( res.data.code == 200 ){
              // console.log(res.data.token)
              //保存用户信息,token
              localStorage.setItem('token',res.data.token);
              localStorage.setItem('userinfo', JSON.stringify( res.data.userinfo ) );
               

              // 请求当前用户的收藏列表
              // 调用vuex中的异步方法发请求异步方法调用同步方法，获取当前用户的收藏列表 并覆盖之前的
              this.$store.dispatch('request_favlist')
              console.log(res.data.userinfo )

            // 请求当前用户的购物车列表
              this.$store.dispatch('request_shopcartlist')

              //自动跳转到首页
              this.$router.push('/');
            }else{
              
              alert('登陆失败!');
              this.$router.push('/register')
            }
          })
        }
      }
    }
  }
  </script>
  
  <style lang='scss' scoped> 
  .login{
    margin: 50px 20px;
  }
  .login .title{
    font-weight: bold;
    text-align: center;
    line-height: 40px;
  }
  .login .block{
    margin: 20px 0;
  }
  .login .block input{
    height: 40px;
    border: 1px solid #ccc;
    border-radius: 20px;
    padding-left: 20px;
    box-sizing: border-box;
    outline: none;
    width: 100%;
  }
  </style>